<template>
  <div>
    <el-card class="box-card">
      <el-button icon="Plus" type="primary" @click="addCategory">
        添加分类
      </el-button>
      <el-table style="margin-top: 10px" border :data="categoryArr">
        <el-table-column
          label="序号"
          width="80px"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column label="分类名称" width="150px" align="center">
          <template #="{ row, $index }">
            <pre>{{ row.name }}</pre>
          </template>
        </el-table-column>
        <el-table-column label="封面图片" width="150px" align="center">
          <template #="{ row, $index }">
            <img
              :src="row.image"
              alt="图片加载失败"
              style="max-width: 100px; max-height: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column label="分类描述" align="center">
          <template #="{ row, $index }">
            <pre>{{ row.description }}</pre>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150px" align="center">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              size="default"
              icon="Edit"
              @click="(event: MouseEvent) => updateCategory(row)"
            ></el-button>
            <el-popconfirm
              :title="`您确定要删除 ${row.tmName} 吗?`"
              width="200px"
              icon="Delete"
              @confirm="removeCategory(row.id)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  size="default"
                  icon="Delete"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!--    对话框组件：在添加分类与修改已有分类的业务时候使用结构-->
      <!--    v-model:属性用户控制对话框的显示与隐藏  -->
      <!--    title:设置对话框左上角标题  -->
      <el-dialog
        v-model="dialogFormVisible"
        :title="categoryParams.id ? '修改分类' : '添加分类'"
      >
        <el-form
          style="width: 80%"
          :model="categoryParams"
          :rules="rules"
          ref="formRef"
        >
          <el-form-item
            label="分类名称"
            label-width="90px"
            label-position="left"
            prop="name"
          >
            <el-input
              placeholder="请您输入分类名称"
              v-model="categoryParams.name"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="分类Logo"
            label-width="90px"
            label-position="left"
            prop="image"
          >
            <!--       el-upload:action属性：图片上传路径   -->
            <!--       el-upload::show-file-list属性：是否显示上传图片列表   -->
            <el-upload
              class="avatar-uploader"
              action="/api/media/admin/fileupload/"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :on-error="handleAvatarError"
            >
              <img
                v-if="categoryParams.image"
                :src="categoryParams.image"
                alt="Logo"
                class="avatar"
                style="width: 150px; height: 150px"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="分类描述"
            label-width="90px"
            label-position="left"
            prop="description"
          >
            <el-input
              placeholder="请您输入分类描述"
              v-model="categoryParams.description"
            ></el-input>
          </el-form-item>
        </el-form>
        <!--      具名插槽-->
        <template #footer>
          <el-button type="primary" size="default" @click="confirm">
            确定
          </el-button>
          <el-button type="danger" size="default" @click="cancel">
            取消
          </el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, type UploadProps } from 'element-plus'
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqHasCategory,
  reqAddCategory,
  reqUpdateCategory,
  reqDeleteCategory,
} from '@/api/category'
import type {
  Category,
  Records,
  CategoryResponseData,
} from '@/api/category/type'

let dialogFormVisible = ref<boolean>(false)
//存储已有分类的数据
let categoryArr = ref<Records>([])
//获取el-form组件实例
let formRef = ref()

let categoryParams = reactive<Category>({
  name: '',
  image: '',
  description: '',
})

//获取已有分类的接口封装为一个函数，在任何情况下获取数据，调用此函数即可
const getHasCategory = async () => {
  let result: CategoryResponseData = await reqHasCategory()
  if (result.code == 200) {
    categoryArr.value = result.data
  }
  console.log(result)
}
//组件挂载完毕钩子———发送一次请求，获取已有分类数据
onMounted(() => {
  getHasCategory()
})

const addCategory = async () => {
  categoryParams.id = undefined
  categoryParams.name = ''
  categoryParams.image = ''
  categoryParams.description = ''

  dialogFormVisible.value = true

  nextTick(() => {
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('image')
    formRef.value.clearValidate('description')
  })
}

//注入了一个参数row
//row：即为当前行对应的分类
const updateCategory = (row: Category) => {
  //清空校验规则的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('image')
  })
  //对话框显示
  dialogFormVisible.value = true
  //ES6语法合并对象
  Object.assign(categoryParams, row)
  console.log(categoryParams)
}

//分类名称校验自定义方法
const validatorName = (rule: any, value: any, callback: any) => {
  //当表单元素触发blur的时候，会触发此方法
  //自定义校验规则
  if (value.length >= 2) {
    //校验通过
    callback()
  } else {
    //校验未通过返回的错误信息
    callback(new Error('分类名称大于等于两位'))
  }
}
//自定义logo图片自定义校验规则方法
const validatorImage = (rule: any, value: any, callback: any) => {
  //如果图片上传
  if (value) {
    callback()
  } else {
    callback(new Error('封面图片务必上传'))
  }
}

const validatorDescription = (rule: any, value: any, callback: any) => {
  if (value.length >= 2) {
    //校验通过
    callback()
  } else {
    callback(new Error('分类描述大于等于两位'))
  }
}

//表单校验规则对象
const rules = {
  name: [
    //required代表这个字段是必须校验的，表现为表单项前面出现一个五角星
    //trigger表示触发校验时机[blur：失去焦点时，change：表单发生变化时]
    { required: true, trigger: 'blur', validator: validatorName },
  ],
  image: [{ required: true, validator: validatorImage }],
  description: [
    { required: true, trigger: 'blur', validator: validatorDescription },
  ],
}

//气泡确认框确定按钮的回调
const removeCategory = async (id: number) => {
  let result: any = await reqDeleteCategory(id)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '分类删除成功',
    })
    //删除成功之后立马再次获取已有分类数
    await getHasCategory()
  } else {
    ElMessage({
      type: 'error',
      message: '删除分类失败',
    })
  }
}

const confirm = async () => {
  // 在发请求之前，要对整个表单进行校验,这里回触发写好的该表单内的所有校验函数
  const isValid = await formRef.value.validate()
  if (!isValid) return // 如果校验失败，直接返回

  try {
    let result: any
    if (categoryParams.id) {
      result = await reqUpdateCategory(categoryParams)
    } else {
      result = await reqAddCategory(categoryParams)
    }
    console.log(result)
    if (result && result.code == 200) {
      // 关闭对话框
      dialogFormVisible.value = false
      // 弹出提示信息
      ElMessage({
        type: 'success',
        message: categoryParams.id ? '修改分类成功' : '添加分类成功',
      })
      // 更新页面信息
      getHasCategory()
    } else {
      ElMessage({
        type: 'error',
        message: categoryParams.id ? '修改分类失败' : '添加分类失败',
      })
    }
  } catch (error) {
    console.error('请求失败:', error)
    ElMessage({
      type: 'error',
      message: '请求失败，请稍后再试',
    })
  }
}
//对话框底部取消按钮
const cancel = () => {
  dialogFormVisible.value = false
}

//上传图片组件->上传图片之前触发的钩子函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  //在图片上传成功之前触发，在上传文件之前可以约束文件类型与大小
  //要求：上传文件格式png|jpg|gif <4MB
  if (
    rawFile.type == 'image/png' ||
    rawFile.type == 'image/jpg' ||
    rawFile.type == 'image/jpeg' ||
    rawFile.type == 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件大小限制：4MB',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件格式限定 png | jpg | jpeg | gif ',
    })
    return false
  }
}

//上传文件成功的钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  categoryParams.image = response.data
  ElMessage({
    type: 'success',
    message: '图片上传成功！',
  })
  formRef.value.clearValidate('image')
}

//失败的钩子
const handleAvatarError: UploadProps['onError'] = (response) => {
  ElMessage({
    type: 'error',
    message: '图片上传失败！请修改文件名避免重名',
  })
}
</script>

<style scoped lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
